package icu.ikuns.servlet;

import icu.ikuns.pojo.Question;
import icu.ikuns.pojo.QuestionBank;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author： Kimariyb
 * @Date：2022/05/22/15:22
 * @Description：
 */
public class QuestionControllerServlet extends HttpServlet {
    public QuestionControllerServlet() {
        super();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        int lastIndex = uri.lastIndexOf("/");
        String action = uri.substring(lastIndex + 1);
        String dispatchUrl = null;
        if ("QuestionList".equals(action)) {
            dispatchUrl = "/WEB-INF/jsp/GeoQuestionList.jsp";
        } else if ("QuestionEdit".equals(action)) {
            String questionId = req.getParameter("questionId");
            if (questionId != null) {
                Question question = new Question();
                question.setQuestionId(questionId);
                try {
                    question.setQuestionClass(Integer.parseInt(req.getParameter("questionClass")));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                question.setQuestionContent(req.getParameter("questionContent"));
                question.setQuestionAnswer(req.getParameter("questionAnswer"));
                QuestionBank questionBank = new QuestionBank();
                int resultCode = questionBank.addQuestion(question);
                String message = "<script>alert('插入记录成功！')</script>";
                if (resultCode < 1) {
                    message = "<script>alert('插入记录失败！')</script>";
                }
                req.setAttribute("message", message);
            }
            dispatchUrl = "/WEB-INF/jsp/QuestionEdit.jsp";
        }
        if (dispatchUrl != null) {
            RequestDispatcher rd = req.getRequestDispatcher(dispatchUrl);
            rd.forward(req, resp);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
